<?php
include_once 'gift_cert/lib/Common.php';
class ImageText
{
	public static function createImage($array)
	{
		$idTpl = substr($array['template'],3);

		// Create the image
		$im = @imagecreatefromjpeg(SYS_PATH."images/gift_cert/tpl".$idTpl.".jpg");

		// Create some colors
		$black = imagecolorallocate($im, 0, 0, 0);
				
		// The text to draw
		$textArr[0] = $array['code'];
		$textArr[1] = "$".$array['amount'];
		$textArr[2] = $array['from'];
		$textArr[3] = $array['to'];
		$textArr[4] = $array['message'];

		// Replace path by your own font path
		$font = SYS_PATH.'gift_cert/data/font/arial.ttf';

		//load config file
		$xmlFile = SYS_PATH."gift_cert/data/config/template.xml";
		if (file_exists($xmlFile)) {
			$xml = simplexml_load_file($xmlFile);
		}

		$result = $xml->xpath("//template[@id=\"".$idTpl."\"]");

		for( $i=0; $i<count($result[0]->item) ;$i++ )
		{
			self::imgText($result[0]->item[$i], $textArr[$i], $im, $black, $font);
		}
		return $im;
	}
	
	public static function createGiftCert($array)
	{
		$im = self::createImage($array);
		$outImg = SYS_PATH."gift_cert/data/output/gift_cert_".$array['code'].".jpg";
		imagejpeg($im, $outImg);
		imagedestroy($im);
		return "gift_cert/data/output/gift_cert_".$array['code'].".jpg";
	}
	
	public static function imgText($item, $text, $im, $black, $font)
	{	
		if(isset($item['cols']) == FALSE)
		{
			imagettftext($im, floatval($item['size']), 0, intval($item['x']), 
									intval($item['y']), $black, $font, $text);
			return;
		}
		$cols = intval($item['cols']);
		
		$rows = isset($item['rows']) == TRUE ? $item['rows'] : 1;
		
		$size = floatval($item['size']);
		$space = isset($item['space']) == TRUE ? $item['space'] : $size *2;
		
		$length = mb_strlen($text);
		if( $length > $cols )
		{
			$arrText = Common::splitByLength($text,$cols);
			
			$count = count($arrText)<$rows?count($arrText):$rows;
			for($i=0; $i< $count; $i++)
			{
				$yy = intval($item['y']) + $i * $space ;
				imagettftext($im, $size , 0, intval($item['x']), $yy, $black, $font, $arrText[$i]);
			}
		}
		else
		{
			imagettftext($im, floatval($item['size']), 0, intval($item['x']), intval($item['y']), $black, $font, $text);
		}
	}
	
	
}
?>